package com.example.partner.fragment;

import static com.baidu.location.LocationClient.setAgreePrivacy;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.example.partner.R;
import com.example.partner.activity.home.NearUsersActivity;

public class NearFragment extends Fragment {

    private LocationClient mLocationClient;
    private MapView mapView;
    private BaiduMap baiduMap;
    double latitude,longitude;
    private boolean isFirstLocate = true;
    private TextView tv_Lat;  // 纬度
    private TextView tv_Lon;  // 经度
    private TextView check; //查看附件用户
    private MyLocationListener myListener = new MyLocationListener();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // SDKInitializer.initialize应该在Fragment的onCreate中调用
        SDKInitializer.initialize(getActivity().getApplicationContext());
        setAgreePrivacy(true);
        // 初始化 LocationClient 类
        try {
            mLocationClient = new LocationClient(getActivity().getApplicationContext());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        mLocationClient.registerLocationListener(myListener);

        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenGps(true);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setIgnoreKillProcess(false);
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
            mLocationClient.start();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_near, container, false);
        mapView = view.findViewById(R.id.bmapView);
        baiduMap = mapView.getMap();
        baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);

        baiduMap.setMyLocationEnabled(true);
        tv_Lon = view.findViewById(R.id.tv_Lon);
        tv_Lat = view.findViewById(R.id.tv_Lat);
        check = view.findViewById(R.id.check);
        check.setOnClickListener(v -> {
            // 启动注册页面的Activity
            Intent intent = new Intent(getContext(), NearUsersActivity.class);
            intent.putExtra("latitude", latitude);
            intent.putExtra("longitude",longitude);
            startActivity(intent);
        });


        return view;
    }

    private class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mapView == null){
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置用户获取到的方向信息，顺时针0-360
                    .direction(location.getDirection()).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            baiduMap.setMyLocationData(locData);
            latitude = location.getLatitude();
            longitude = location.getLongitude();

            tv_Lat.setText(String.valueOf(latitude));
            tv_Lon.setText(String.valueOf(longitude));
            if (isFirstLocate) {
                MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(new LatLng(latitude, longitude));
                baiduMap.animateMapStatus(update);
                update = MapStatusUpdateFactory.zoomTo(16f);
                baiduMap.animateMapStatus(update);
                isFirstLocate = false;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
        mapView.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }
}
